package com.example.mytimeclock;

import java.io.FileOutputStream;
import java.util.ArrayList;

import android.content.Context;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;

class MyListAdapter extends BaseAdapter{// 리스트 아답터 클래스(커스텀 리스트뷰를 위해)
	Context maincon;			
	LayoutInflater Inflater;		// 전개
	ArrayList<MyItem> arSrc;	// 어레이 리스트
	int layout;
	//MyItem myItem = new MyItem();
	
	public MyListAdapter(Context maincon, int layout, ArrayList<MyItem> arSrc) {// 생성자
		this.maincon = maincon;
		this.Inflater = (LayoutInflater) maincon.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.arSrc = arSrc;
		this.layout = layout;
	}

	public int getCount() {
		return arSrc.size();
	}

	public Object getItem(int position) {
		return arSrc.get(position).name;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		final int pos = position;
		if(convertView == null){
			convertView = Inflater.inflate(layout, parent, false);
		}
		
		MyItem.chrono = (Chronometer) convertView.findViewById(R.id.timerlist_chrono);
		//TextView chronoText = (TextView) convertView.findViewById(R.id.timerlist_ellapse);
		arSrc.get(pos).chrono.start();
		
		TextView txt = (TextView) convertView.findViewById(R.id.timerlist_name);// 일정이름
		txt.setText(arSrc.get(position).name);
		
		final Button btnStop = (Button) convertView.findViewById(R.id.timerlist_stop_btn);// 정지버튼
		
		final TextView txtClockstart = (TextView) convertView.findViewById(R.id.timerlist_clockstart);//현재시각
		final TextView txtClockend = (TextView) convertView.findViewById(R.id.timerlist_clockend);
		txtClockstart.setText(arSrc.get(pos).clock);//시작시간 출력
		
		btnStop.setOnClickListener(new Button.OnClickListener() {// 종료버튼 누르면
			public void onClick(View v) {
				String str = arSrc.get(pos).name+" "+arSrc.get(pos).clock+"~"+TimerMain.nowTime();
				Toast.makeText(maincon, str, Toast.LENGTH_SHORT).show();
				try{
					FileOutputStream fos = maincon.openFileOutput(
							Environment.getExternalStorageDirectory().getAbsolutePath()+"/myday.txt", Context.MODE_PRIVATE);
					fos.write(str.getBytes());
					fos.close();
					Toast.makeText(maincon, arSrc.get(pos).name+"저장완료", Toast.LENGTH_SHORT).show();
				}catch(Exception e){;}
				arSrc.get(pos).chrono.stop();
				
				btnStop.setText("완료");// 버튼 텍스트 변경
				txtClockend.setText(TimerMain.nowTime());// 종료시간 출력
			}
		});
		return convertView;
	} // getView 메소드 끝
} // 리스트 어댑터 클래스 끝
